package com.ljy.my_study.leetcode.两数之和II_输入有序数组;

import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author lijunying
 * @date 2020/7/20 10:32
 */
public class TestMain {
    public static void main(String[] args) {
//        int[] numbers=new int[]{5,25,75};
//        System.out.println(Arrays.toString(new TestMain().twoSum(numbers,100)));
//        int[] numbers=new int[]{0,0,3,4};
//        System.out.println(Arrays.toString(new TestMain().twoSum(numbers,0)));
        int[] numbers=new int[]{2, 7, 11, 15};
        System.out.println(Arrays.toString(new TestMain().twoSum(numbers,9)));
    }

    public int[] twoSum(int[] numbers, int target) {
        Map<Integer,Integer> map=new LinkedHashMap<>();
        for(int i=0;i<numbers.length;i++){
            if(!map.containsKey(numbers[i])){
                map.put(numbers[i],i);
            }
        }
        for(Map.Entry<Integer,Integer> e:map.entrySet()){
            if(map.get(target-e.getKey())==null){
                continue;
            }
            int index=e.getValue();
            int nextIndex=map.get(target-e.getKey());
            if(index==nextIndex){
                if(index+1>=numbers.length){
                    return null;
                }
                if(numbers[index]+numbers[index+1]==target){
                    return new int[]{index+1,index+2};
                }
            }else{
                return new int[]{index+1,nextIndex+1};
            }

        }
        return null;
    }
}
